package com.yxy.controller.user;

import com.yxy.common.Result;
import com.yxy.constant.RequestMapperConstant;
import com.yxy.pojo.dto.UserDTO;
import com.yxy.pojo.dto.UserLoginDTO;
import com.yxy.pojo.entity.User;
import com.yxy.pojo.vo.UserLoginVO;
import com.yxy.pojo.vo.UserVO;
import com.yxy.properties.JwtProperties;
import com.yxy.service.UserService;
import com.yxy.service.VisitService;
import com.yxy.utils.AreaUtil;
import com.yxy.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController("userUserController")
@RequestMapping(RequestMapperConstant.USER_REQUEST_MAPPER + "client")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private VisitService visitService;

    /**
     * 注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        log.info("注册用户信息：{}", userDTO);
        userService.add(userDTO);
        return Result.success("注册成功");
    }

    /**
     * 登陆
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登陆：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("u_id", user.getId());
        String token = JwtUtil.createJwt(jwtProperties.getUserSecretKey(), jwtProperties.getUserExpire(), claims);
        String ip = AreaUtil.getIp();
        String area = AreaUtil.getArea(ip);
        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .name(user.getName())
                .token(token)
                .avatar(user.getAvatar())
                .area(area)
                .build();
        // 登陆成功后，把用户的信息记录到Visit表中，进行访问量统计
        visitService.add(user.getId());
        return Result.success("登陆成功", vo);
    }

    /**
     * 验证用户token
     *
     * @param token
     * @return
     */
    @GetMapping("/checkUserToken")
    public Result checkUserToken(@RequestParam String token) {
        try {
            JwtUtil.parseJwt(jwtProperties.getUserSecretKey(), token);
            log.info("checkUserToken：有效");
        } catch (Exception e) {
            log.info("checkUserToken：无效");
            return Result.error(401, "expired");
        }
        return Result.success("", null);
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/getUserById")
    public Result<UserVO> getUserById(int id){
        log.info("根据id查询用户信息：{}", id);
        UserVO vo = userService.getUserById(id);
        return Result.success("", vo);
    }

    /**
     * 修改用户信息
     * @param userDTO
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody UserDTO userDTO){
        log.info("修改用户信息：{}", userDTO);
        userService.update(userDTO);
        return Result.success("修改成功");
    }

    /**
     * 验证密码
     * @param password
     * @return
     */
    @GetMapping("/verifyPwd")
    public Result verifyPwd(Integer userId, String password){
        log.info("用户id：{}, 验证密码：{}", userId, password);
        Boolean falg = userService.verifyPwd(userId, password);
        return Result.success("", falg);
    }

    /**
     * 添加用户访问量
     * @param userId
     * @return
     */
    @PutMapping("/addVisitor/{userId}")
    public Result addVisitor(@PathVariable int userId){
        log.info("添加用户访问量：{}", userId);
        userService.addVisitor(userId);
        return Result.success("");
    }

    /**
     * 校验手机号
     * @param username
     * @param phone
     * @return
     */
    @GetMapping("/verifyPhone")
    public Result verifyPhone(String username, String phone){
        log.info("账号：{}，校验手机号：{}", username, phone);
        Boolean flag = userService.verifyPhone(username, phone);
        return Result.success("", flag);
    }

    /**
     * 重置密码
     * @param userDTO
     * @return
     */
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody UserDTO userDTO){
        log.info("重置密码：{}", userDTO);
        userService.resetPwd(userDTO);
        return Result.success("重置密码成功");
    }
}
